export const renderer = createRenderer({
  createElement(tag) {
    return document.createElement(tag);
  },
  setElementText(el, text) {
    el.textContent = text;
  },
  insert(el, parent, anchor = null) {
    parent.insertBefore(el, anchor);
  },
});

function createRenderer(options) {
  const { createElement, setElementText, insert } = options;
  function render(vnode, container) {
    console.log("vnode==", vnode, container._vnode);
    if (vnode) {
      patch(container._vnode, vnode, container);
    } else {
      if (container._vnode) {
        container.innerHTML = "";
      }
    }
    container._vnode = vnode;
    console.log("container==", container);
  }
  function patch(n1, n2, container) {
    if (!n1) {
      // n1不存在 仅挂载
      mountElement(n2, container);
    } else {
      // n1存在意味着打补丁
    }
  }
  function mountElement(vnode, container) {
    const el = createElement(vnode.type);
    if (typeof vnode.children === "string") {
      setElementText(el, vnode.children);
    }
    insert(el, container);
  }

  return {
    render,
  };
}
